package org.hughie.http;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.hughie.api.FundApisMapping;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author hughie.cheng
 * @date 2024/2/29
 */
@Slf4j
@Component
public class HttpInvoker implements IHttpInvoker {

    private RestTemplate restTemplate;

    public HttpInvoker(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }


    @Override
    public <M> M get(FundApisMapping fundApisMapping, String... args) {
        return get(String.format(fundApisMapping.getUrl(), args), fundApisMapping.getClz());
    }

    @Override
    public <M> List<M> getList(FundApisMapping fundApisMapping, String... args) {
        return getList(String.format(fundApisMapping.getUrl(), args), fundApisMapping.getClz());
    }

    public <M> M get(String url, Class<?> M) {
        String forObject = restTemplate.getForObject(url, String.class);
        JSONObject jsonObject = JSON.parseObject(forObject);
        return (M) JSON.to(M, jsonObject.get("Datas"));
    }

    public <M> List<M> getList(String url, Class<?> M) {
        String forObject = restTemplate.getForObject(url, String.class);
        if (forObject != null && forObject.contains("(")) {
            // forObject = "{ \"FundListFMN\": " + forObject.substring(forObject.indexOf("(") + 1, forObject.lastIndexOf(")")) + "}";
            forObject = forObject.substring(forObject.indexOf("(") + 1, forObject.lastIndexOf(")"));
        }
        JSONArray jsonArray = JSON.parseObject(forObject).getJSONArray("Datas");

        return (List<M>) JSONArray.parseArray(jsonArray.toString(), M);
    }

}
